package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-11-08
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        // 判断参数
        if (dto == null ||
                (StringUtils.isEmpty(dto.getPhone())
                        && StringUtils.isEmpty(dto.getPassword())
                        && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 手机号和密码不为空的情况下,使用手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            // 根据用户名查询用户
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 如果用户存在
            // 获取用户数据库中保存的盐
            String salt = one.getSalt();
            // 拼接用户传入的密码+盐
            String pwd = dto.getPassword() + salt;
            // 做MD5计算
            String md5Pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
            // 将计算出的MD5字符串与数据库中保存的密码比较
            if (!md5Pwd.equals(one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 密码一致,需要使用JWT生成token
            Map<String, Object> claimMap = new HashMap<>();
            // 可以将当前登录用户的id,name放入到自定义负载中
            claimMap.put("userId", one.getId());
            claimMap.put("name", one.getName());
            String token = AppJwtUtil.getToken(claimMap);
            // 定义返回的结果
            Map<String, Object> map = new HashMap<>();
            // 过滤用户的敏感信息
            one.setPhone("");
            one.setSalt("");
            one.setPassword("");
            map.put("user", one);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        // 如果设备号是否不为空,使用0来生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> claimMap = new HashMap<>();
            // 可以将当前登录用户的id,name放入到自定义负载中
            claimMap.put("userId", "0");
            String token = AppJwtUtil.getToken(claimMap);
            // 定义返回的结果
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 获取当前登录用户信息
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        int followId = 0;

        // 构建关注记录
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(user.getUserId());
        userFollow.setUserName(user.getName());
        userFollow.setLevel(1);
        userFollow.setCreatedTime(new Date());
        // 获取作者信息
        ResponseResult<ApAuthor> authorResponseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (authorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = authorResponseResult.getData();
            if (apAuthor != null) {
                userFollow.setFollowId(apAuthor.getUserId());
                userFollow.setFollowName(apAuthor.getName());
                followId = apAuthor.getUserId();
                // 判断操作是关注还是取消关注
                LambdaUpdateWrapper<ApUserFollow> query = new LambdaUpdateWrapper<>();
                query.eq(ApUserFollow::getUserId, user.getUserId());
                query.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
                if (dto.getOperation() == 0) {
                    // 关注
                    // 保存用户关注信息  判断是否已经有历史记录
                    ApUserFollow one = followService.getOne(query);
                    if (one == null) {
                        // 新增
                        followService.save(userFollow);
                    }
                } else {
                    // 取消关注
                    // 删除对应的记录
                    followService.remove(query);
                }
            }
        }

        // 将操作行为发送到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(followId);
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setOperation(dto.getOperation());

        String msg = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehaviorTopic, msg);

        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
